package controllers

import (
	"anban/service"
	"anban/utils/wechat"
	"encoding/xml"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/url"
	"os"
	"time"
)

type WechatController struct {
	beego.Controller
}

func (c *WechatController) Prepare() {
	c.EnableXSRF = false
}

// 安伴公众号接收微信通知
func (c *WechatController) AnBan() {
	//echoStr := c.GetString("echostr")
	timestamp := c.GetString("timestamp")
	nonce := c.GetString("nonce")
	signature := c.GetString("signature")
	genSignature := wechat.GetWechatSignature(timestamp, nonce)
	if signature != genSignature { // 验证是否是微信发过来的消息，如果不是，直接返回
		c.Ctx.WriteString("")
		return
	}
	//c.Ctx.WriteString(echoStr)
	//return
	var eventMsg wechat.EventMsg
	if err := xml.Unmarshal(c.Ctx.Input.RequestBody, &eventMsg); err != nil {
		logs.Info("微信返回出错：", err)
		c.Ctx.WriteString("success")
		return
	}
	switch eventMsg.MsgType {

	case "event": // 事件消息
		switch eventMsg.Event {

		case "subscribe": // 订阅事件
			replyContent := eventMsg.HandleSubscribe()
			c.Ctx.WriteString(replyContent)
			return

		case "CLICK": // 点击菜单事件
			replyContent := eventMsg.HandleClickKeyword()
			c.Ctx.WriteString(replyContent)
			return

		case "unsubscribe": // 取消订阅事件
			p := map[string]interface{}{}
			p["openId"] = eventMsg.FromUserName
			user := service.GetUserInfo(p)
			if user.Id > 0 {
				input := url.Values{
					"id": {fmt.Sprintf("%d", user.Id)},
					"subscribe_status": {"2"},
					"unsubscribe_time": {time.Now().Format("2006-01-02 15:04:05")},
				}
				service.EditUser(input)
			}
		}

	case "text": // 用户发送文本消息
		replyContent := eventMsg.HandleKeyword()
		c.Ctx.WriteString(replyContent)
		return

	}

	c.Ctx.WriteString("success")
}

func (c *WechatController) DomainAuth() {
	f, _ := os.Open("./static/MP_verify_IklbbXqr38x99lLf.txt")
	content, _ := ioutil.ReadAll(f)
	c.Ctx.WriteString(string(content))
}

func (c *WechatController) MiniAuth() {
	c.Ctx.WriteString("1fd907075a271379f6b40137511a0165")
}